<template>
  <PageWrapper>
    <a-card class="m-b-16px">
      <a-row :gutter="[16, 16]">
        <a-col :span="6">
          <a-form-item :label="t('sys.device.columns.status')">
            <a-select
              allow-clear
              v-model:value="formState.deviceStatus"
              :placeholder="t('sys.form.placeholder.status')"
              option-label-prop="label"
              style="width: 100%"
            >
              <a-select-option value="1" :label="t('sys.configuration.normal')">
                {{ t('sys.configuration.normal') }}
              </a-select-option>
              <a-select-option value="0" :label="t('sys.configuration.blockUp')">
                {{ t('sys.configuration.blockUp') }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item :label="t('sys.script.columns.deviceCode')">
            <a-input
              allow-clear
              v-model:value="formState.deviceNo"
              placeholder="请输入设备码/机器码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item :label="t('sys.script.columns.name')">
            <a-input
              allow-clear
              v-model:value="formState.deviceAlias"
              placeholder="请输入设备名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item :label="t('sys.script.columns.grouping')">
            <a-input allow-clear v-model:value="formState.deviceGroup" placeholder="请输入分组" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="4" :offset="20" style="display: flex; justify-content: flex-end">
          <a-space>
            <a-button @click="queryRef" :icon="h(SearchOutlined)" type="primary">
              {{ t('sys.form.placeholder.inquire') }}
            </a-button>
            <a-button @click="openOfflineConfig" :icon="h(SettingOutlined)" type="default">
              {{ t('sys.configuration.offlineConfig') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-card>
      <a-collapse>
        <a-collapse-panel key="1" :header="t('sys.devstatistics.label')">
          <p
            >{{ t('sys.devstatistics.deviceAllCount') }} :
            {{ t('sys.devstatistics.deviceAllCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceNodeAllCount') }} :
            {{ t('sys.devstatistics.deviceNodeAllCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceOffLineCount') }} :
            {{ t('sys.devstatistics.deviceOffLineCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceOnLineCount') }} :
            {{ t('sys.devstatistics.deviceOnLineCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceRestartIngCount') }} :
            {{ t('sys.devstatistics.deviceRestartIngCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceKillIngCount') }} :
            {{ t('sys.devstatistics.deviceKillIngCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceRestartFailCount') }} :
            {{ t('sys.devstatistics.deviceRestartFailCountDetails') }}</p
          >
          <p
            >{{ t('sys.devstatistics.deviceKillFailCount') }} :
            {{ t('sys.devstatistics.deviceKillFailCountDetails') }}</p
          >
        </a-collapse-panel>
      </a-collapse>
      <a-alert class="mb-2 mt-2" type="info" show-icon>
        <template #message>
          <div>
            <span>
              {{ t('sys.devstatistics.title') }}:
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceAllCount') }} : {{ StatisticsInifo.deviceAllCount }}
                {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceNodeAllCount') }} :
                {{ StatisticsInifo.deviceNodeAllCount }} {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceOffLineCount') }} :
                {{ StatisticsInifo.deviceOffLineCount }}
                {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceOnLineCount') }}
                {{ StatisticsInifo.deviceOnLineCount }}
                {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceRestartIngCount')
                }}{{ StatisticsInifo.deviceRestartIngCount }}
                {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceKillIngCount') }} :
                {{ StatisticsInifo.deviceKillIngCount }} {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceRestartFailCount') }} :
                {{ StatisticsInifo.deviceRestartFailCount }}
                {{ t('sys.configuration.strip') }}
              </span>
              <span class="ml-2">
                {{ t('sys.devstatistics.deviceKillFailCount') }} :
                {{ StatisticsInifo.deviceKillFailCount }}
                {{ t('sys.configuration.strip') }}
              </span>
            </span>
          </div>
        </template>
      </a-alert>
      <a-table
        @change="handleTableChange"
        :pagination="pagination"
        :loading="loading"
        bordered
        rowKey="id"
        :showExpandColumn="false"
        :scroll="{ x: 1500 }"
        :columns="configcolumns"
        :dataSource="dataSource"
        v-model:expandedRowKeys="expandedRowKeys"
        @expand="onExpand"
      >
        <template #expandedRowRender="{ record }">
          <a-table
            :dataSource="scriptmonitoringData"
            @change="ndoehandleTableChange"
            :pagination="nodepagination"
            :columns="monitoringColumns"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex == 'status'">
                <a-tag v-if="record.status == 0" color="red">{{ t('sys.analysis.offLine') }}</a-tag>
                <a-tag v-else-if="record.status == 2" color="green">{{
                  t('sys.configuration.busy')
                }}</a-tag>
                <a-tag v-else-if="record.status == 1" color="orange">{{
                  t('sys.configuration.leisure')
                }}</a-tag>
                <span v-else></span>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" @click="openNodesDetails(record.id)">
                  {{ t('sys.configuration.particulars') }}
                </a-button>
                <a-button @click="setShowNodeClick(record)" type="link">
                  {{ t('sys.configuration.set') }}
                </a-button>
                <a-dropdown v-model:open="dropdownnodeVisibles[record.id]" trigger="click">
                  <a-button type="link" @click.prevent>
                    {{ t('sys.configuration.action') }}
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item key="1">
                        <a-popconfirm
                          @confirm="startconfirm(record, 'start')"
                          :title="t('sys.configuration.Isstart')"
                          :ok-text="t('sys.configuration.comfig')"
                          :cancel-text="t('sys.configuration.cancel')"
                        >
                          <a-button type="link">{{ t('sys.configuration.start') }}</a-button>
                        </a-popconfirm>
                      </a-menu-item>
                      <a-menu-item key="2">
                        <a-popconfirm
                          @confirm="startconfirm(record, 'restart')"
                          :title="t('sys.configuration.Isstart')"
                          :ok-text="t('sys.configuration.comfig')"
                          :cancel-text="t('sys.configuration.cancel')"
                        >
                          <a-button type="link">{{ t('sys.analysis.restart') }}</a-button>
                        </a-popconfirm>
                      </a-menu-item>
                      <a-menu-item key="3">
                        <a-popconfirm
                          @confirm="startconfirm(record, 'kill')"
                          :title="t('sys.configuration.Iscease')"
                          :ok-text="t('sys.configuration.comfig')"
                          :cancel-text="t('sys.configuration.cancel')"
                        >
                          <a-button type="link">{{ t('sys.configuration.cease') }}</a-button>
                        </a-popconfirm>
                      </a-menu-item>
                      <a-menu-item v-for="(item, index) in record.cmds" :key="item.cmdContent">
                        <a-popconfirm
                          class="custom-popconfirm"
                          @confirm="startconfirm(record, item.cmdContent)"
                          :title="t('sys.configuration.IS') + item.cmdName"
                          :ok-text="t('sys.configuration.comfig')"
                          :cancel-text="t('sys.configuration.cancel')"
                        >
                          <a-button type="link">{{ item.cmdName }}</a-button>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </template>
          </a-table>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'avatarUrl'">
            <a-image width="30px" :src="record.avatarUrl" />
          </template>
          <template v-if="column.dataIndex === 'deviceStatus'">
            <a-tag v-if="record.deviceStatus == 0" color="red">
              {{ t('sys.analysis.offLine') }}
            </a-tag>
            <a-tag v-if="record.deviceStatus == 1" color="green">
              {{ t('sys.analysis.onLine') }}
            </a-tag>
            <a-tag v-if="record.deviceStatus == 2" color="orange">
              {{ t('sys.analysis.uncollected') }}
            </a-tag>
            <a-tag v-if="record.deviceStatus == 3" color="red">
              {{ t('sys.analysis.restartError') }}
            </a-tag>
            <a-tag v-if="record.deviceStatus == 4" color="orange">
              {{ t('sys.configuration.Stopping') }}
            </a-tag>
            <a-tag v-if="record.deviceStatus == 5" color="red">
              {{ t('sys.configuration.ceaseError') }}
            </a-tag>
          </template>

          <template v-if="column.dataIndex === 'status'">
            <div>
              <span class="status-label"> {{ t('sys.device.columns.status') }} : </span>
              <a-tag v-if="record.deviceStatus == 0" color="orange">
                {{ t('sys.configuration.blockUp') }}
              </a-tag>
              <a-tag v-if="record.deviceStatus == 1" color="green">
                {{ t('sys.configuration.normal') }}
              </a-tag>
            </div>
            <div>
              <span class="status-label">{{ t('sys.device.columns.blockUp') }} : </span>
              <a-tag v-if="record.useStatus == 0" color="orange">
                {{ t('sys.configuration.blockUp') }}
              </a-tag>
              <a-tag v-if="record.useStatus == 1" color="green">
                {{ t('sys.configuration.normal') }}
              </a-tag>
            </div>
          </template>

          <template v-if="column.dataIndex === 'progress'"
            >{{ record.currentProcess }}/{{ record.totalProcess }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <!--            <a-button @click="detailsClick(record)" type="link">-->
            <!--              {{ t('sys.configuration.particulars') }}-->
            <!--            </a-button>-->
            <a-button @click="setShowClick(record)" type="link">
              {{ t('sys.configuration.set') }}
            </a-button>
            <!-- <a-button @click="toggleMonitoring(record.id)" type="link"> {{ t('sys.configuration.monitoring') }} </a-button> -->
            <a-button @click="toggleMonitoring(record, 1)" type="link">
              {{ t('sys.configuration.monitoring') }}
            </a-button>
            <a-dropdown v-model:open="dropdownVisibles[record.id]" trigger="click">
              <a-button type="link" @click.prevent>
                {{ t('sys.configuration.action') }}
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="2">
                    <a-popconfirm
                      @confirm="ressenddevicemand(record, 'restart')"
                      :title="t('sys.configuration.Isstart')"
                      :ok-text="t('sys.configuration.comfig')"
                      :cancel-text="t('sys.configuration.cancel')"
                    >
                      <a-button type="link">{{ t('sys.analysis.restart') }}</a-button>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item key="3">
                    <a-popconfirm
                      @confirm="ressenddevicemand(record, 'kill')"
                      :title="t('sys.configuration.Iscease')"
                      :ok-text="t('sys.configuration.comfig')"
                      :cancel-text="t('sys.configuration.cancel')"
                    >
                      <a-button type="link">{{ t('sys.configuration.cease') }}</a-button>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item v-for="(item, index) in record.cmds" :key="item.id">
                    <a-popconfirm
                      class="custom-popconfirm"
                      @confirm="ressenddevicemand(record, item.cmdContent)"
                      :title="t('sys.configuration.IS') + item.cmdName"
                      :ok-text="t('sys.configuration.comfig')"
                      :cancel-text="t('sys.configuration.cancel')"
                    >
                      <a-button type="link">{{ item.cmdName }}</a-button>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <a-popconfirm
              @confirm="delteDevive(record)"
              :title="t('sys.configuration.IsDelete')"
              :ok-text="t('sys.configuration.comfig')"
              :cancel-text="t('sys.configuration.cancel')"
            >
              <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
      <a-modal
        centered
        @ok="ModalShow = false"
        bordered
        width="80%"
        :title="t('sys.configuration.deviceDetails')"
        v-model:open="ModalShow"
      >
        <a-descriptions bordered :size="size">
          <a-descriptions-item :label="t('sys.device.columns.deviceID')">{{
            detailsRecord.id
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.script.columns.deviceCode')">{{
            detailsRecord.deviceNo
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.script.columns.name')">{{
            detailsRecord.deviceAlias
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.script.columns.grouping')">{{
            detailsRecord.grouping
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.log.deviceNodeNum')">{{
            detailsRecord.nodes
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.log.lastHeartbeatTime')">{{
            detailsRecord.lastHeartbeatTime
          }}</a-descriptions-item>
          <a-descriptions-item label="MAC">{{ detailsRecord.deviceMac }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.configuration.describe')">{{
            detailsRecord.deviceDesc
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.log.onlinestate')">
            <a-tag v-if="detailsRecord.deviceStatus == 0" color="orange">
              {{ t('sys.configuration.blockUp') }}
            </a-tag>
            <a-tag v-if="detailsRecord.deviceStatus == 1" color="green">
              {{ t('sys.configuration.normal') }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="IP">{{ detailsRecord.IPAddress }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.script.columns.version')">{{
            detailsRecord.version
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.device.columns.userId')">{{
            detailsRecord.attributionTccount
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.device.columns.remck')">{{
            detailsRecord.remark
          }}</a-descriptions-item>
          <a-descriptions-item :label="t('sys.device.columns.validTime')">
            {{ detailsRecord.validTime }}
          </a-descriptions-item>
        </a-descriptions>
        <!-- <div>
          <h3>设备心跳与状态实时监控</h3>
          <div class="status-indicator">
            <span :style="{ backgroundColor: isOnline ? 'green' : 'red' }" class="dot"></span>
            当前状态: {{ isOnline ? '在线' : '离线' }}
          </div>
          <a-table :dataSource="heartbeatData" :columns="columns" :pagination="false" />
        </div> -->
      </a-modal>
      <a-drawer
        v-model:open="setShowDarwer"
        class="custom-class"
        root-class-name="root-class-name"
        :root-style="{ color: 'blue' }"
        style="color: red"
        :size="'large'"
        :title="t('sys.configuration.set')"
        placement="right"
      >
        <a-form
          :model="detailsRecord"
          name="basic"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item :label="t('sys.device.columns.deviceID')">
            <a-input v-model:value="detailsRecord.id" disabled />
          </a-form-item>

          <a-form-item label="Mac">
            <a-input v-model:value="detailsRecord.deviceMac" disabled />
          </a-form-item>
          <a-form-item :label="t('sys.log.lastHeartbeatTime')">
            <a-input v-model:value="detailsRecord.lastHeartbeatTime" disabled />
          </a-form-item>
          <a-form-item :label="t('sys.device.columns.devicecode')">
            <a-input v-model:value="detailsRecord.deviceNo" />
          </a-form-item>
          <a-form-item :label="t('sys.script.columns.name')">
            <a-input v-model:value="detailsRecord.deviceAlias" />
          </a-form-item>
          <a-form-item :label="t('sys.script.columns.grouping')">
            <a-input v-model:value="detailsRecord.deviceGroup" />
          </a-form-item>
          <a-form-item :label="t('sys.configuration.describe')">
            <a-input v-model:value="detailsRecord.deviceDesc" />
          </a-form-item>
          <a-form-item label="IP">
            <a-input v-model:value="detailsRecord.deviceIp" />
          </a-form-item>
          <a-form-item :label="t('sys.device.columns.version')">
            <a-input v-model:value="detailsRecord.deviceVersion" />
          </a-form-item>
          <a-form-item :label="t('sys.device.columns.remck')">
            <a-input v-model:value="detailsRecord.remark" />
          </a-form-item>
          <a-form-item :label="t('sys.code.columns.account')">
            <a-select v-model:value="detailsRecord.accountId">
              <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">
                {{ item.account }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :label="t('sys.log.onlinestate')">
            <a-select v-model:value="detailsRecord.deviceStatus">
              <a-select-option value="0">
                {{ t('sys.analysis.offLine') }}
              </a-select-option>
              <a-select-option value="1">
                {{ t('sys.analysis.onLine') }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :label="t('sys.log.deviceNodeNum')">
            <a-input v-model:value="detailsRecord.deviceNodeNum" />
          </a-form-item>
        </a-form>

        <div class="m-t-10px m-b-10px"> {{ t('sys.configuration.configuretask') }} </div>
        <a-divider />
        <div style="display: flex; justify-content: flex-end">
          <a-button @click="addDevice" type="primary" size="small">
            {{ t('sys.configuration.add') }}
          </a-button>
        </div>
        <a-table
          class="m-t-10px m-b-10px"
          :pagination="false"
          bordered
          :columns="scriptColumns"
          :dataSource="scriptData"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'name'">
              <span v-for="(item, index) in scriptList" :key="index">
                <span v-if="item.scriptId == record.scriptId">{{ item.label }}</span>
              </span>
            </template>
            <template v-if="column.dataIndex === 'quantity'">
              <a-input-number v-model:value="record.num"></a-input-number>
            </template>
            <template v-if="column.dataIndex === 'action'">
               <a-button @click="EditScript(record)" type="link"> {{ t('sys.configuration.edit') }} </a-button>
              <a-popconfirm
                :title="t('sys.configuration.IsDelete') + '！'"
                @confirm="deleteScript(record)"
                :ok-text="t('sys.configuration.comfig')"
                :cancel-text="t('sys.configuration.cancel')"
              >
                <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
        <div class="m-t-10px m-b-10px"> {{ t('sys.configuration.configurecmd') }} </div>
        <a-divider />
        <div style="display: flex; justify-content: flex-end">
          <a-button @click="addDevicecmd" type="primary" size="small">
            {{ t('sys.configuration.add') }}
          </a-button>
        </div>
        <a-table
          class="m-t-10px m-b-10px"
          :pagination="false"
          bordered
          :columns="scriptColumnscmd"
          :dataSource="scriptDatacmd"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'cmdName'">
              <a-select
                v-model:value="record.cmdId"
                :placeholder="t('sys.configuration.pleasechoose') + t('sys.menu.columns.type')"
                :options="dcmdList"
                :field-names="{ label: 'cmdName', value: 'id' }"
                style="width: 100%"
              />
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-popconfirm
                :title="t('sys.configuration.IsDelete') + '！'"
                @confirm="deletecmd(record)"
                :ok-text="t('sys.configuration.comfig')"
                :cancel-text="t('sys.configuration.cancel')"
              >
                <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
        <a-form name="basic" :layout="'vertical'" autocomplete="off">
          <a-form-item :wrapper-col="{ span: 24 }">
            <a-button @click="devEditsubmit" type="primary">
              {{ t('sys.configuration.confirm') }}
            </a-button>
          </a-form-item>
        </a-form>
      </a-drawer>
      <a-drawer
        v-model:open="setShownodeDarwer"
        class="custom-class"
        root-class-name="root-class-name"
        :root-style="{ color: 'blue' }"
        style="color: red"
        :size="'large'"
        :title="t('sys.configuration.set')"
        placement="right"
      >
        <div class="m-t-10px m-b-10px"> {{ t('sys.configuration.configurecmd') }} </div>
        <a-divider />
        <div style="display: flex; justify-content: flex-end">
          <a-button @click="addDevicecmd" type="primary" size="small">
            {{ t('sys.configuration.add') }}
          </a-button>
        </div>
        <a-table
          class="m-t-10px m-b-10px"
          :pagination="false"
          bordered
          :columns="scriptColumnscmd"
          :dataSource="scriptDatacmd"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'cmdName'">
              <a-select
                v-model:value="record.cmdId"
                :placeholder="t('sys.configuration.pleasechoose') + t('sys.menu.columns.type')"
                :options="dcmdList"
                :field-names="{ label: 'cmdName', value: 'id' }"
                style="width: 100%"
              />
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-popconfirm
                :title="t('sys.configuration.IsDelete') + '！'"
                @confirm="deletecmd(record)"
                :ok-text="t('sys.configuration.comfig')"
                :cancel-text="t('sys.configuration.cancel')"
              >
                <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
        <a-form name="basic" :layout="'vertical'" autocomplete="off">
          <a-form-item :wrapper-col="{ span: 24 }">
            <a-button @click="devnoodeEditsubmit" type="primary">
              {{ t('sys.configuration.confirm') }}
            </a-button>
          </a-form-item>
        </a-form>
      </a-drawer>
      <a-modal
        v-model:open="addDeviceModalVisible"
        :title="t('sys.configuration.confirm') + t('sys.script.title')"
        @ok="handleAddDeviceConfirm"
        @cancel="handleAddDeviceCancel"
      >
        <a-form layout="vertical">
          <a-form-item :label="t('sys.configuration.select') + t('sys.script.title')">
            <a-select
              v-model:value="selectedScript"
              :placeholder="t('sys.configuration.selectScript')"
              :options="scriptList"
              :field-names="{ label: 'label', value: 'scriptId' }"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item :label="t('sys.configuration.inputNum')">
            <a-input-number
              v-model:value="inputQuantity"
              :placeholder="t('sys.configuration.selectNum')"
              style="width: 100%"
              min="1"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal
        width="50%"
        v-model:open="logShow"
        :title="t('sys.configuration.log')"
        @ok="logShow = false"
      >
        <a-tabs v-model:activeKey="activeKey" @change="logtabChange">
          <a-tab-pane key="1" :tab="t('sys.configuration.courseLog')">
            <a-table
              :loading="tasklogLoading"
              :pagination="false"
              :columns="processLogColumns"
              :dataSource="taskLogdataSource"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex == 'type'">
                  <a-tag color="blue"> {{ t('sys.configuration.courseLog') }} </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button @click="detailsClick(record)" type="link">
                    {{ t('sys.configuration.particulars') }}
                  </a-button>
                  <a-popconfirm
                    :title="t('sys.configuration.IsDelete')"
                    :ok-text="t('sys.configuration.comfig')"
                    :cancel-text="t('sys.configuration.cancel')"
                  >
                    <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" :tab="t('sys.configuration.runLog')">
            <a-table
              :loading="tasklogLoading"
              :pagination="false"
              :columns="processLogColumns"
              :dataSource="taskLogdataSource"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex == 'type'">
                  <a-tag color="blue"> {{ t('sys.configuration.runLog') }} </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button @click="detailsClick(record)" type="link">
                    {{ t('sys.configuration.particulars') }}
                  </a-button>
                  <a-popconfirm
                    :title="t('sys.configuration.IsDelete')"
                    :ok-text="t('sys.configuration.comfig')"
                    :cancel-text="t('sys.configuration.cancel')"
                  >
                    <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="3" :tab="t('sys.configuration.errorLog')">
            <a-table
              :loading="tasklogLoading"
              :pagination="false"
              :columns="processLogColumns"
              :dataSource="taskLogdataSource"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex == 'type'">
                  <a-tag color="blue"> {{ t('sys.configuration.errorLog') }} </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button @click="detailsClick(record)" type="link">
                    {{ t('sys.configuration.particulars') }}
                  </a-button>
                  <a-popconfirm
                    :title="t('sys.configuration.IsDelete')"
                    :ok-text="t('sys.configuration.comfig')"
                    :cancel-text="t('sys.configuration.cancel')"
                  >
                    <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="4" :tab="t('sys.configuration.stopLog')">
            <a-table
              :loading="tasklogLoading"
              :pagination="false"
              :columns="processLogColumns"
              :dataSource="taskLogdataSource"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex == 'type'">
                  <a-tag color="blue"> {{ t('sys.configuration.stopLog') }} </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-button @click="detailsClick(record)" type="link">
                    {{ t('sys.configuration.particulars') }}
                  </a-button>
                  <a-popconfirm
                    :title="t('sys.configuration.IsDelete')"
                    :ok-text="t('sys.configuration.comfig')"
                    :cancel-text="t('sys.configuration.cancel')"
                  >
                    <a-button danger type="link"> {{ t('sys.configuration.delete') }} </a-button>
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="5" :tab="t('sys.configuration.heartbeat')">
            <VisHeartbeat />
          </a-tab-pane>
        </a-tabs>
      </a-modal>
      
      <!-- 离线配置 Drawer -->
      <a-drawer
        v-model:open="offlineConfigDrawerVisible"
        class="custom-class"
        root-class-name="root-class-name"
        :root-style="{ color: 'blue' }"
        style="color: red"
        :size="'large'"
        :title="t('sys.configuration.offlineConfig')"
        placement="right"
      >
        <a-form
          :model="offlineConfigForm"
          name="offlineConfig"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item :label-col="{ span: 24 }" :label="'添加邮箱'">
            <a-row :gutter="[20, 20]" style="display: flex; align-items: center">
              <a-col
                :key="value"
                v-for="(key, value, index) in offlineConfigList"
                class="flex items-center"
                :span="24"
              >
                <PlusOutlined
                  v-if="index === Object.keys(offlineConfigList).length - 1"
                  class="mr-[10px]"
                  @click="addOfflineConfigItem(index)"
                />
                <MinusOutlined
                  v-if="index != Object.keys(offlineConfigList).length - 1"
                  class="mr-[10px]"
                  @click="deleteOfflineConfigItem(value)"
                />
                <a-input
                  v-model:value="offlineConfigList[value]"
                  placeholder="请输入"
                />
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 24 }">
            <a-button @click="saveOfflineConfig" type="primary">
              {{ t('sys.configuration.confirm') }}
            </a-button>
          </a-form-item>
        </a-form>
      </a-drawer>
    </a-card>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, h } from 'vue';
  import { SearchOutlined, SettingOutlined, PlusOutlined, MinusOutlined } from '@ant-design/icons-vue';
  import { PageWrapper } from '@/components/Page';
  import { configcolumns, scriptColumns, monitoringColumns } from './account.data';
  import {
    getScriptsPageAPI,
    getCmdAPI,
    deleteDeviceScriptAPI,
    addScriptAPI,
  } from '@/api/demo/script';
  import VisHeartbeat from './compunt/VisHeartbeat.vue';
  import {
    getFbDeviceAPI,
    delFbDeviceAPI,
    getUserlsitAPI,
    updatefbDeviceApi,
    updatecmdDeviceApi,
    deviceNodedetailinfo,
    updatefbDevicenodepageApi,
    senddevicemand,
    deviceNodeupdate,
    getstatistics,
    senddeviceNodecmd, 
    updatescript,
    getDeviceEmailAPI,
    addDeviceEmailAPI,
  } from '@/api/demo/device';

  import type { UnwrapRef } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { message } from 'ant-design-vue';

  const { t } = useI18n();
  interface FormState {
    deviceStatus: string;
    deviceNo: string;
    deviceAlias: string;
    deviceGroup: string;
  }
  const StatisticsInifo = ref<any>({});
  const dropdownVisibles = ref({});
  const dropdownnodeVisibles = ref({});
  const processLogColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: t('sys.device.columns.time'), dataIndex: 'nodeTime', key: 'nodeTime' },
    { title: t('sys.analysis.columns.type'), dataIndex: 'type', key: 'type' },
    { title: '日志信息', dataIndex: 'info', key: 'info' },
  ];
  const activeKey = ref('1');
  const formState: UnwrapRef<FormState> = reactive({
    deviceStatus: '',
    deviceNo: '',
    deviceAlias: '',
    deviceGroup: '',
  });
  const scriptColumnscmd = ref([
    {
      title: t('sys.commandSet.title'),
      dataIndex: 'cmdName',
      width: 150,
    },
    {
      title: t('sys.configuration.action'),
      dataIndex: 'action',
      width: 50,
    },
  ]);
  const startconfirm = (record, it) => {
    dropdownnodeVisibles.value[record.id] = false;
    senddeviceNodecmd({ deviceMac: record.mac, deviceNode: record.node, cmd: it }).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.api.operationSuccess'));
        toggleMonitoring(itemRecord.value, 0);
      }
    });
  };
  const ressenddevicemand = (record, it) => {
    dropdownVisibles.value[record.id] = false;
    senddevicemand({ deviceMac: record.deviceMac, cmd: it }).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.analysis.restartSucces'));
        init();
      }
    });
  };
  const taskLogdataSource = ref([]);
  const expandedRowKeys = ref<any[]>([]);
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const nodepagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const userList = ref<any[]>([]);
  const init1 = async () => {
    const value = await getUserlsitAPI();
    userList.value = value.data;
  };
  const queryRef = () => {
    pagination.value.current = 1
    init();
  };
  const onExpand = (expanded: boolean, record: any) => {
    const index = expandedRowKeys.value.indexOf(record.id);
    if (expanded && index === -1) {
      expandedRowKeys.value.push(record.id);
    } else if (!expanded && index !== -1) {
      expandedRowKeys.value.splice(index, 1);
    }
  };
  const scriptmonitoringData = ref<any[]>([]);
  const itemRecord = ref<any>({});
  const toggleMonitoring = (record, it) => {
    if (it == 1) {
      nodepagination.value.current = 1;
    }
    itemRecord.value = record;
    updatefbDevicenodepageApi({
      deviceId: record.id,
      deviceAlias: record.deviceAlias,
      size: nodepagination.value.pageSize,
      current: nodepagination.value.current,
    }).then((res) => {
      if (res.code == 200) {
        scriptmonitoringData.value = res.data.records;
        expandedRowKeys.value = [record.id];
        nodepagination.value.total = res.data.total;
      }
    });
  };
  const delteDevive = async (record) => {
    const result = await delFbDeviceAPI({
      deviceId: record.id,
    });
    if (result.code == 200) {
      message.success(t('sys.configuration.deleteSucces'));
      init();
    }
  };

  const handleTableChange = (e) => {
    pagination.value = e;
    init();
  };

  const ndoehandleTableChange = (e) => {
    nodepagination.value = e;
    toggleMonitoring(itemRecord.value, 0);
  };
  const size = ref('default');
  const setShowDarwer = ref(false);
  const setShownodeDarwer = ref(false);
  const scriptData = ref<any[]>([]);
  const setShowClick = (record) => {
    setShowDarwer.value = true;
    detailsRecord.value = record;
    getDcmdList(record, 1);
    if (record.scripts && record.scripts.length > 0) {
      scriptData.value = record.scripts;
    }
    if (record.cmds && record.cmds.length > 0) {
      scriptDatacmd.value = record.cmds;
    } else {
      scriptDatacmd.value = [];
    }
  };
  const detailsnodeRecord = ref<any>({});
  const setShowNodeClick = (record) => {
    setShownodeDarwer.value = true;
    detailsnodeRecord.value = record;
    getDcmdList(record, 2);
    if (record.cmds && record.cmds.length > 0) {
      scriptDatacmd.value = record.cmds;
    } else {
      scriptDatacmd.value = [];
    }
  };
  const deletecmd = (index) => {
    scriptDatacmd.value = scriptDatacmd.value.filter((item) => item !== index);
  };
  const ModalShow = ref(false);
  const detailsRecord = ref<any>({});
  const detailsClick = (record) => {
    ModalShow.value = true;
    detailsRecord.value = record;
    if (record.scripts && record.scripts.length > 0) {
      scriptData.value = record.scripts;
    }
  };
  const dataSource = ref();
  const scriptList = ref<any[]>([]);
  const loading = ref(true);
  const tasklogLoading = ref(true);
  const addDeviceModalVisible = ref(false); // 控制弹框显示
  const selectedScript = ref(null); // 存储选择的脚本
  const inputQuantity = ref(null); // 存储输入的数量
  const selectedNode = ref(null);
  const logShow = ref(false);
  
  // 离线配置相关
  const offlineConfigDrawerVisible = ref(false);
  const offlineConfigForm = ref({});
  const offlineConfigList = ref({
    email0: '',
  });
  const openNodesDetails = (node) => {
    selectedNode.value = node;
    logShow.value = true;
    infoTab();
  };
  const infoTab = () => {
    tasklogLoading.value = true;
    deviceNodedetailinfo({ id: selectedNode.value, type: activeKey.value }).then((res) => {
      if (res.code == 200) {
        taskLogdataSource.value = res.data;
        tasklogLoading.value = false;
      }
    });
  };
  const logtabChange = (e) => {
    infoTab();
  };
  const dcmdList = ref([]);
  const getDcmdList = (record, it) => {
    getCmdAPI({ cmdType: it, deviveId: record.id }).then((res) => {
      if (res.code == 200) {
        dcmdList.value = res.data;
      }
    });
  };
  const stattisticsinit = () => {
    getstatistics().then((res) => {
      StatisticsInifo.value = res.data;
    });
  };
  const init = () => {
    loading.value = true;
    getScriptList();
    stattisticsinit();
    getDeviceList();
    // postUserListPage({ size: pagination.value.pageSize, current: pagination.value.current }).then(
    //   (res) => {
    //     if (res.code == 200) {
    //       dataSource.value = res.data.records;
    //       pagination.value.total = res.data.total;
    //       loading.value = false;
    //     }
    //   },
    // );
  };
  const devEditsubmit = () => {
    updatefbDeviceApi(detailsRecord.value).then((res) => {
      if (res.code == 200) {
        updatecmdDeviceApi({ id: detailsRecord.value.id, cmds: scriptDatacmd.value }).then(
          (res1) => {
            if (res1.code == 200) {
              message.success('修改成功');
              init();
              setShowDarwer.value = false;
            }
          },
        );
        updatescript( scriptData.value ).then((res) => {});
      }
    });

  };
  const devnoodeEditsubmit = () => {
    deviceNodeupdate({ id: detailsnodeRecord.value.id, nodeCmds: scriptDatacmd.value }).then(
      (res) => {
        if (res.code == 200) {
          message.success('修改成功');
          toggleMonitoring(itemRecord.value, 0);
          setShownodeDarwer.value = false;
        }
      },
    );
  };
  const getDeviceList = async () => {
    const result = (await getFbDeviceAPI({
      size: pagination.value.pageSize,
      current: pagination.value.current,
      ...formState,
    })) as { items: any[]; total: number };
    dataSource.value = result.items;
    pagination.value.total = result.total;
    loading.value = false;
  };
  const getScriptList = async () => {
    const result = (await getScriptsPageAPI({ page: 1, pageSize: 9999 })) as {
      items: any[];
      total: number;
    };
    scriptList.value = result.items.map((item) => ({
      ...item,
      scriptId: item.id,
      label: item.name,
    }));
  };
  const addDevice = () => {
    addDeviceModalVisible.value = true; // 显示弹框
  };
  const scriptDatacmd = ref<any[]>([]);
  const addDevicecmd = () => {
    scriptDatacmd.value.push({
      cmdId: null,
      deviceId: detailsRecord.value.id,
    });
  };
  const handleAddDeviceConfirm = () => {
    const selectedOption = {
      scriptId: scriptList.value.find((item) => item.scriptId === selectedScript.value).scriptId,
      deviceId: detailsRecord.value.id,
    };

    if (!selectedOption || !inputQuantity.value) {
      return;
    }
    const obj = { ...selectedOption, num: inputQuantity.value };
    addScriptAPI(obj).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.api.operationSuccess'));
        scriptData.value.push(obj);
        handleAddDeviceCancel();
        init();
      }
    });
  };
  const handleAddDeviceCancel = () => {
    addDeviceModalVisible.value = false; // 关闭弹框
    inputQuantity.value = null;
    selectedScript.value = null;
  };
  const deleteScript = (index) => {
    deleteDeviceScriptAPI(index.id).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.configuration.deleteSucces'));
        scriptData.value = scriptData.value.filter((item) => item !== index);
        init();
      }
    });
  };

  const EditScript = (record) => {
    // 编辑脚本的逻辑
    console.log('编辑脚本:', record);
  };

  // 离线配置相关方法
  const openOfflineConfig = async () => {
    offlineConfigDrawerVisible.value = true;
    
    try {
      // 调用获取邮箱接口
      const result = await getDeviceEmailAPI();
      
      if (result.code === 200 && result.data && Array.isArray(result.data)) {
        // 将返回的邮箱列表转换为配置对象
        const emailConfig: any = {};
        result.data.forEach((email, index) => {
          emailConfig[`email${index}`] = email;
        });
        
        // 如果列表为空，至少添加一个空输入框
        if (result.data.length === 0) {
          emailConfig.email0 = '';
        }
        
        offlineConfigList.value = emailConfig;
      } else {
        // 如果接口调用失败，初始化一个空的邮箱输入框
        offlineConfigList.value = {
          email0: '',
        };
      }
    } catch (error) {
      console.error('获取邮箱列表失败:', error);
      // 出错时初始化一个空的邮箱输入框
      offlineConfigList.value = {
        email0: '',
      };
    }
  };

  const addOfflineConfigItem = (index) => {
    // 检查 offlineConfigList 是否存在
    if (!offlineConfigList.value) {
      console.error('offlineConfigList 未正确初始化');
      return;
    }

    // 获取当前对象的所有键
    const keys = Object.keys(offlineConfigList.value);

    // 确保键名唯一性：使用当前最大索引+1来创建新键
    const maxIndex = keys.reduce((max, key) => {
      const match = key.match(/email(\d+)/);
      if (match) {
        const num = parseInt(match[1], 10);
        return Math.max(max, num);
      }
      return max;
    }, -1);

    const newKey = `email${maxIndex + 1}`;

    // 添加新的空值字段
    offlineConfigList.value[newKey] = '';

    // 强制触发响应式更新
    offlineConfigList.value = { ...offlineConfigList.value };
  };

  const deleteOfflineConfigItem = (key) => {
    // 检查 offlineConfigList 是否存在
    if (!offlineConfigList.value) {
      console.error('offlineConfigList 未正确初始化');
      return;
    }

    // 检查要删除的键是否存在
    if (Object.prototype.hasOwnProperty.call(offlineConfigList.value, key)) {
      // 删除对应的 key 字段
      delete offlineConfigList.value[key];

      // 强制触发响应式更新
      offlineConfigList.value = { ...offlineConfigList.value };
    } else {
      console.warn(`要删除的键 ${key} 不存在`);
    }
  };

  const saveOfflineConfig = async () => {
    try {
      // 将配置对象转换为邮箱数组
      const emailList = Object.values(offlineConfigList.value).filter(email => email.trim() !== '');
      
      // 调用添加邮箱接口
      const result = await addDeviceEmailAPI(emailList);
      
      if (result.code === 200) {
        message.success('邮箱配置保存成功');
        offlineConfigDrawerVisible.value = false;
      } else {
        message.error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存邮箱配置失败:', error);
      message.error('保存失败，请重试');
    }
  };
  onMounted(() => {
    init();
    init1();
  });
</script>
<style scoped lang="scss">
  .status-label {
    width: 100px;
  }

  .ant-card-body:first-child {
    padding: 12px 10px 6px;
  }

  .ant-card-body:last-child {
    padding: 6px;
  }

  .status-indicator {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }

  .dot {
    width: 10px;
    height: 10px;
    margin-right: 8px;
    border-radius: 50%;
  }
</style>
